package net.area80.object
{
	import flash.utils.describeType;

	public class ReadStringObject
	{
		public static function bracesQuote (o:Object):String {
			var typeXML:XML = describeType(o);
			var s:String = ""+String(typeXML.@name).split("::").join(".")+" {";
			var isFirst:Boolean = true;
			for each (var node:XML in typeXML.variable) {
				s +=  ((!isFirst)?", " : "") + [node.@name] + ":\"" + String(o[node.@name]).split('""').join('\\"') + "\"";
				if (isFirst) isFirst = false;
			}
			s += "}"
			return s;
		}
		public static function easyToRead (o:Object, currentPos:uint=0):String {
			var endstatement:String = ",";
			if(o) {
				var typeXML:XML = describeType(o);
				//trace(o);
				if(typeXML) {
				//	trace(typeXML);
					var type:String = String(typeXML.@name).split("::").join(".");
					
					
					if(type.toLowerCase()=="string") return String("\""+o+"\"");
					if(type.toLowerCase()=="array" || type.toLowerCase().indexOf("__as3__.vec.vector")==0) return easyToReadArray(o,currentPos);
					if(type.toLowerCase()=="int" || type.toLowerCase()=="uint" || type.toLowerCase()=="number") return String(o);
					var tab:String = "";
					for(var i:uint=0;i<currentPos;i++){
						tab += "\t";
					}
					currentPos = currentPos+1;
					
					var s:String = type+" {";
					var count:uint = 0;
					for each (var node:XML in typeXML.variable) {
						if(count==0) s+="\n";
						if(count>0) {
							s += endstatement+"\n";
						}
						s +=  tab+"\t" + [node.@name] + " : " + ReadStringObject.easyToRead(o[node.@name],currentPos) ;
						count++;
						
					}
					s += ((count>0) ? "\n"+tab : '')+"}";
					return s;
				} else {
					return String(o);
				}
			} else {
				return "null";
			}
		}
		public static function easyToReadArray (o:Object, currentPos:uint=0):String {
			if(o.hasOwnProperty("length")) {
				var tab:String = "";
				var i:uint = 0;
				for(i=0;i<currentPos;i++){
					tab += "\t";
				}
				currentPos = currentPos+1;
				var type:String = "Vector";
				if(o is Array) type = "Array";
				var s:String = type+" [";
				for(i=0;i<o.length;i++) {
					if(i==0) s+="\n";
					if(i>0) {
						s += ",\n";
					}
					s +=  tab+"\t" + ReadStringObject.easyToRead(o[i],currentPos);
				}
				s += ((i>0) ? "\n"+tab : '')+"]";
				return s;
			} else {
				throw new Error("not array or vector");
				return null;
			}
		}
	}
}